% Hash function
-module(hash).
-export([hash_full/1, hash/1, hash_bounded/2]).

% Hash a value using sha hashing. 
hash_full_old(Data) ->
    case is_atom(Data) of
        true  -> Data2 = atom_to_list(Data);
        false -> Data2 = Data
    end,
    HashedValue   = crypto:sha(Data2),
    binary:decode_unsigned(HashedValue).

% Hash a value using sha hashing twice, 
% with salting in between the rounds.
hash_full(Data) ->
    case is_atom(Data) of
        true  -> Data2 = atom_to_list(Data);
        false -> Data2 = Data
    end,
    {ok, Salt}    = application:get_env(db, hashsalt),
    HashedValue   = crypto:sha(Data2),
    HashedString  = binary:bin_to_list(HashedValue),
    SaltedString  = Salt ++ HashedString ++ Salt,
    HashedValue2  = crypto:sha(SaltedString),
    binary:decode_unsigned(HashedValue2).

% Hash a value using sha hashing. The value is 
% adjusted with modulo given hashsize.
% Hashsize is given by environment variable. 
hash(Data) ->
    {ok,HashSize} = application:get_env(db, hashsize),
    hash_full(Data) rem intmath:pow(2,HashSize).

% Hash a value using sha hashing. The value is 
% adjusted with modulo given hashsize.
% Hashsize is given by parameter. 
hash_bounded(Data, HashSize) ->
    hash_full(Data) rem intmath:pow(2, HashSize).

